import os
import zipfile
import shutil
import time

class zipHelper():

    @staticmethod
    def zipDir(src, out):
        """
        压缩多个文件夹
        :param src: 要压缩的多个文件夹/文件路径
        :param out: 压缩文件保存到的zip文件
        :return: 无
        """
        zip = zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED)

        for name in src:  
            if name.find('~') != -1:
                name = name.replace('~', os.environ['HOME'])
            if name.find('$CURRENTUSER') != -1:
                name = name.replace('$CURRENTUSER', os.getlogin())
            if os.path.exists(name) == True:
                if os.path.isdir(name) == True:
                    # 只保留最后一级目录，把目录进行压缩
                    dirs = name.split(os.sep)
                    parent = dirs[-2]
                    for path, dirnames, filenames in os.walk(name):
                        fpath = path.replace(name, '')
                        for filename in filenames:
                            zip.write(os.path.join(path, filename), os.path.join(parent, fpath, filename))
                elif os.path.isfile(name) == True:
                    zip.write(name, os.path.basename(name))

        zip.close()

    @staticmethod
    def unzipDir(file, outs):
        """
        压缩指定文件夹
        :param file: 要解压缩zip文件名(包括路径)
        :param outs: 解压到的目录(多个)
        :return: 无
        """
        tmpdir = os.path.join(os.path.dirname(file), 'tmp')
        shutil.rmtree(tmpdir, ignore_errors=True)
        os.mkdir(tmpdir)
        zf = zipfile.ZipFile(file)
        zf.extractall(path = tmpdir)
        for name in outs:  
            if name.find('~') != -1:
                name = name.replace('~', os.environ['HOME'])
            if name.find('$CURRENTUSER') != -1:
                name = name.replace('$CURRENTUSER', os.getlogin())
            if os.path.exists(name) == True:
                if os.path.isdir(name) == True:
                    dirs = name.split(os.sep)
                    parent = dirs[-2]
                    shutil.rmtree(name, ignore_errors=True)
                    time.sleep(1)
                    shutil.copytree(os.path.join(tmpdir, parent), name) 
                elif os.path.isfile(name) == True:
                    os.unlink(name)
                    shutil.copy(os.path.join(tmpdir, os.path.basename(name)), name) 
        

        shutil.rmtree(tmpdir)
